package com.suxin.reactor;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Tang
 * @classname ServerSocket
 * @description [  ]
 * @date 2021/2/1 22:24
 */
public class MyBioServerSocket implements Runnable{

    private int port = 8888;

    @Override
    public void run() {
        try {
            ServerSocket ss = new ServerSocket(port);
            System.out.println(Thread.currentThread().getName() + "启动成功!");
            while (!Thread.interrupted()) {
                System.out.println("线程" + Thread.currentThread().getId() + "等待连接...");
                new Thread(new Handler(ss.accept()));
                System.out.println("线程" + Thread.currentThread().getId() + "获取连接成功...");
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }

    static class Handler implements Runnable {

        private Socket socket;

        public Handler(Socket socket) {
            this.socket = socket;
        }
        @Override
        public void run() {
            try {
                InputStream inputStream = socket.getInputStream();
                byte[] bt = new byte[Integer.MAX_VALUE];
                int len = 0;
                while ((len = inputStream.read(bt)) > 0) {
                    System.out.println(Thread.currentThread().getId() + ":收到的消息为：--->" + new String(bt, 0, len));
                    // do process()...
//                    socket.getOutputStream().write(null);
                }
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}